package com.znyj.cloud.device.task;

import com.znyj.cloud.device.task.model.ControlTaskModel;
import com.znyj.cloud.device.task.sender.ControlDataSender;
import org.apache.log4j.Logger;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

/**
 * Created by gaoliwei02 on 17/6/3.
 */
@Component
public class ControlTaskMapping extends AbstractTaskMapping<ControlTaskModel> {
    private static final Logger logger = Logger.getLogger(ControlTaskMapping.class);

    @Resource
    private ControlDataSender controlDataSender;

    //@Scheduled(cron = "0/2 * * * * ?")
    @Scheduled(fixedDelay = 500)
    @Override
    public void sendTasks() {
        //把所有有任务设备的任务发送出去
        for (Map.Entry<String, List<ControlTaskModel>> entry : taskMap.entrySet()) {

            //获取此deviceid
            String deviceId = entry.getKey();
            //设备的的任务列表
            List<ControlTaskModel> controlTaskModels = entry.getValue();

            //如果这个deviceid的任务数为0，除掉这个deviceid
            if (controlTaskModels.size() == 0) {
                removeDevice(deviceId);
                continue;
            }

            //从这个deviceId中获取他的ctx通道
            if (!OnlineDeviceInfoMapping.contain(deviceId)) {
                logger.error("send task to device but not online:{} " + deviceId);
                continue;
            }

            for (int cnt = 0; cnt < controlTaskModels.size(); cnt++) {
                //借助异步发送器发送获取的队列第一个非延时
                if (controlTaskModels.get(cnt).getSkipDelay() <= 0) {
                    controlDataSender.send(controlTaskModels.get(cnt), OnlineDeviceInfoMapping.getChannelByDeviceId(deviceId));//发送list的第一个任务
                    controlTaskModels.remove(controlTaskModels.get(cnt));
                    break;
                } else {
                    controlTaskModels.get(cnt).decSkipDelay();
                }
            }
            //logger.info("did:" + deviceId + " size:" + controlTaskModels.size());
//            //借助异步发送器发送获取的队列第一个
//            if (controlTaskModels.get(0).getSkipDelay() <= 0) {
//                controlDataSender.send(controlTaskModels.get(0), OnlineDeviceInfoMapping.getChannelByDeviceId(deviceId));//发送list的第一个任务
//                logger.info("Control send to device: " + deviceId);
//                controlTaskModels.remove(controlTaskModels.get(0));
//            } else {
//                controlTaskModels.get(0).decSkipDelay();
//            }
        }
    }
}
